# -*- coding: utf-8 -*-

import cgi
import os
import xml.etree.cElementTree as etree
from cgi import escape
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import facebook
from facebook import FacebookError

_FbIconImage = 'http://img25.imageshack.us/img25/5409/akomismoicon4.jpg'
_FbBGImage = 'http://img37.imageshack.us/img37/4136/akomismopixel.jpg'
_FbLastError = ''
_FbAppURL = 'http://apps.facebook.com/akomismo/'
_FbApiKey = 'a8dfbf5416044ed379eaf8a4bb424fdf'
_FbSecret = 'e950aa7805c18e5fa6223367810a5e3d'
_FbTemplateBundleId = 187470245249

class Pledge(db.Model):
    authorfid = db.IntegerProperty()
    author = db.StringProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)


class MainPage(webapp.RequestHandler):
    def get(self):
        self.redirect(_FbAppURL)
        return 
    def post(self):
        fb = facebook.Facebook(_FbApiKey,_FbSecret)
        if(fb.check_session(self.request)) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<fb:redirect url="' + url + '"></fb:redirect>')
            return
            
        path = os.path.join(os.path.dirname(__file__), 'main.html')
        self.response.out.write(template.render(path, {'iconurl':_FbIconImage,'bgurl':_FbBGImage,'lasterror': _FbLastError,'appurl':_FbAppURL}))


class MakePledge(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(_FbApiKey,_FbSecret)
        
        if(fb.check_session(self.request)) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<fb:redirect url="' + url + '"></fb:redirect>')
            return
        
        info = fb.users.getInfo( fb.uid, ['uid', 'name',])[0]
        
        
        userpledge = self.request.get('content')
        userpledge = userpledge.encode('ascii', 'xmlcharrefreplace')
        if(userpledge!=''):

            beok = fb.status.set('work1' )
            beok = fb.feed.publishStoryToUser('work2','gogo','http://www.qlkj.net.cn/ShowPic.ashx?CategoryID=1&ItemID=20928&Size=O&PicNO=1','http://www.qlkj.net.cn/ShowPic.ashx?CategoryID=1&ItemID=20928&Size=O&PicNO=1')

            pledge = Pledge()
            pledge.authorfid = info['uid']
            pledge.author = info['name']
            pledge.content = userpledge 
            beok = fb.feed.publishUserAction(_FbTemplateBundleId,'{"images":[{"src":"http://img5.imageshack.us/img5/7762/akomismoicon2.jpg","href":"http://apps.facebook.com/akomismo"},{"src":"http://img5.imageshack.us/img5/7762/akomismoicon2.jpg","href":"http://apps.facebook.com/akomismo"}],"pledge":"'+userpledge+'"}',[],1)
            pledge.put()

            
            self.response.out.write(beok)
            self.response.out.write('OK')
            return

        self.redirect('/inputerror')

class InviteFriends(webapp.RequestHandler):
    def post(self):
        if(self.request.get('skipped')):
            self.redirect('/')
            return
            
        fb = facebook.Facebook(_FbApiKey,_FbSecret)
        
        if(fb.check_session(self.request)) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<fb:redirect url="' + url + '"></fb:redirect>')
            return
            
        content='<fb:name firstnameonly="true" shownetwork="false" uid="profileowner"></fb:name> wants to invite you to Di Ako Papayag, <fb:req-choice label="Join Di Ako Papayag now!" url="'+_FbAppURL+'"></fb:req-choice>'
        invitation_content = escape(content, True)
        
        fbsql = "SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='%s') AND is_app_user = 1" % fb.uid
        result = fb.fql.query(fbsql)
            
        if result and isinstance(result, list): 
            friends_list = map(lambda x: str(x['uid']), result) 
        else: 
            friends_list = []

        exclude_ids = ','.join(friends_list) 

        path = os.path.join(os.path.dirname(__file__), 'invite.html')
        self.response.out.write(template.render(path, {'iconurl':_FbIconImage,'bgurl':_FbBGImage,'lasterror': _FbLastError,'appurl':_FbAppURL,'invitation_content':invitation_content,'exclude_ids':exclude_ids}))        
        return 
        
class InputOk(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(_FbApiKey,_FbSecret)
        
        if(fb.check_session(self.request)) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<fb:redirect url="' + url + '"></fb:redirect>')
            return
        
        _FbLastError = 'Your pledge has been posted!';
        path = os.path.join(os.path.dirname(__file__), 'main.html')
        self.response.out.write(template.render(path, {'iconurl':_FbIconImage,'bgurl':_FbBGImage,'lasterror': _FbLastError}))
            
class InputError(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(_FbApiKey,_FbSecret)
        
        if(fb.check_session(self.request)) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<fb:redirect url="' + url + '"></fb:redirect>')
            return
        
        _FbLastError = 'You must enter a pledge by using numbers, letters and spaces only.';
        path = os.path.join(os.path.dirname(__file__), 'main.html')
        self.response.out.write(template.render(path, {'iconurl':_FbIconImage,'bgurl':_FbBGImage,'lasterror': _FbLastError}))
        
        
        
application = webapp.WSGIApplication(
                                     [
                                      ('/', MainPage),
                                      ('/pledge', MakePledge),
                                      ('/ok', InputOk),
                                      ('/inputerror', InputError),
                                      ('/invite', InviteFriends),
                                      ],
                                     debug=True)

def main():
    run_wsgi_app(application)
    
if __name__ == "__main__" :
    main()       
